package com.zhenhe.api.login;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.zhenhe.api.exception.ApiAuthenticationException;
import com.zhenhe.core.common.global.Global;
import com.zhenhe.core.common.global.signIn.LoginInfoUtil;
import com.zhenhe.core.dto.APIResultDto;
import com.zhenhe.core.entity.TUserEntity;

/**
 * api登陆类
 * @author hl
 *
 */
public class APILoginUtil {

	private static ThreadLocal<TUserEntity> threadLocal = new ThreadLocal<TUserEntity>();
	
	private static final Logger LOG = LoggerFactory.getLogger(APILoginUtil.class);
	
	public static TUserEntity getLogintuser(){
		TUserEntity tuserEntity = threadLocal.get();
		if(tuserEntity==null){
			LOG.error("用户未登录");
			throw new ApiAuthenticationException("用户未登录");
		}
		return tuserEntity;
	}
	
	public static void putLogintuser(TUserEntity tuser){
		threadLocal.set(tuser);
		LoginInfoUtil.setLoginCellphone(tuser.getCellphone());
	}
	
	/**
	 * 未登陆返回消息
	 * @return
	 */
	public static String unAuthorityJsonString(){
		return buildJsonString(Global.getMessage("api.error.unlogin"), APIResultDto.UN_LOGIN );
	}
	
	/**
	 * 登陆超时返回消息 
	 * @return
	 */
	public static String authorityTimeoutJsonString(){
		return buildJsonString(Global.getMessage("api.error.login.timeout"), APIResultDto.LOGIN_TIMEOUT );
	}
	
	/**
	 * 登陆超时返回消息 
	 * @return
	 */
	public static String blanklistJsonString(){
		return buildJsonString(Global.getMessage("api.error.blacklist"), APIResultDto.BLANKLIST );
	}
	
	/**
	 * 登陆超时返回消息 
	 * @return
	 */
	public static String systemErrorJsonString(){
		return buildJsonString(Global.getMessage("api.error.system.error"), APIResultDto.SYSTEM_ERROR );
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private static String buildJsonString(String msg,Integer status){
		APIResultDto result = new APIResultDto<>();
		result.setData(null);
		result.setStatus(status);
		result.setErrorCode("-1");
		result.setMessage(msg);
		return JSONObject.toJSONString(result);
	}
}
